<?php 

error_reporting(E_ALL);
/*
dispatch.php
--------------
dispatches the requests

*/
set_include_path(get_include_path().':./:./templates/:./responses/:./lib/');

require 'config/namespaces.php';
require 'config/routes.php';
require 'config/mimetypes.php';

function process_request($urls, $namespaces, $mimetypes)
{
	$accept_mimetypes = explode(',',$_SERVER['HTTP_ACCEPT']);
	$request_uri = str_replace($_SERVER['QUERY_STRING'],'', $_SERVER['REQUEST_URI']);
	$request_uri = str_replace('?','', $request_uri);
	$parts = explode('.',$request_uri);
	$url_ext = array_pop($parts);
	$request_uri= (isset($mimetypes[$url_ext]))? implode('.', $parts) : $request_uri;
	$ext = (isset($mimetypes[$url_ext]))? $url_ext : 'html' ;
	$mimetype = (isset($mimetypes[$ext]))? $mimetypes[$ext] : 'text/html';
	header("Content-type: {$mimetype}; charset=utf-8");
	
	foreach($urls as $re => $array)
	{
		
		if(preg_match('@'.$re.'@', $request_uri, $matches) and ($matches[0] == $request_uri))
		{

			/*
			inject values from the url regex into the array of parameters
			*/
			foreach($array as $k => $v)
			{
				if(is_string($v))
				{
					preg_match_all('@\$[0-9]+@i', $v, $num_matches );
					foreach($num_matches[0] as $num )
					{
						$array[$k] = str_replace($num, $matches[substr($num,1)], $v);
					}
				}

			}
			$array['namespaces'] = $namespaces;
			$array['filename_extension'] = $ext;
			$array['request_uri'] = $request_uri;
			if(isset($array['class']))
			{
				
				require 'responses/'.strtolower($array['class']).'.php';
				eval('$obj = new '.$array['class'].'($array);');
			
				/* check if the request method exists in the class, and in HTTP */
				if(method_exists($obj, $_SERVER['REQUEST_METHOD']) and in_array($_SERVER['REQUEST_METHOD'], array('GET','POST','HEAD','PUT','DELETE')))
				{
					eval('$output = $obj->'.$_SERVER['REQUEST_METHOD'].'();');

					return ($output);
				}
				else /* return a 405 with an Allow header stating allowed http methods */
				{
					header("HTTP/1.0 405 Method Not Allowed");
					$php_methods = get_class_methods($array['class']);
					$http_methods = array('GET','POST','PUT','DELETE','HEAD');
					$allowed_methods = array_intersect($php_methods, $http_methods);
					header("Allow: ".implode(' ,', $allowed_methods));
					return "Method Not Allowed";
				}
			}
			else
			{
				return file_get_contents('templates/'.$array['template'].'.'.$ext);
			}
		}
	
	}
	
		/* no url has matched, so we return a 404 */
		$code = "HTTP/1.0 404 Not Found";
		header($code);
		require_once 'responses/page.php';
		$array['template'] = 'Errors/404';
		$array['namespaces'] = $namespaces;
		$array['filename_extension'] = $ext;
		$array['request_uri'] = $request_uri;
		$error_page  = new Page($array);
		return $error_page->GET();
	
}

echo process_request($urls, $namespaces, $mimetypes);
?>